<?php

namespace admin;

    use C\lib\Db;
    use C\lib\Oss;
    use C\mod\bag;
    use C\mod\orderPiece;
    use C\mod\pieceState;
    use C\mod\user;
    use C\mod\worker;
    use C\mod\workerType;
    use C\mod\city;

    class hr extends ctr {

        const listRows = 50;   // 每页显示的几条记录
        // --- 员工 ---

        public function worker() {

            if($worker = $this->getLogAds()) {
                $this->render('hr/worker');
            }

        }

        // --- 员工列表获取 ajax ---

        public function workersGet() {
            $this->writeJson(1);exit();
            global $_WORKER_TYPE;

            if($worker = $this->getLogWorker()) {

                $searchRealname = isset($_GET['search']) && trim($_GET['search']) != '' ? trim($_GET['search']) : '';
                $stmt1 = DB::query('select count(id) count from cd_worker '.($searchRealname?' where realname like "%'.$searchRealname.'%"':''));
                if($stmt1 && $stmt1->rowCount()) {

                    $data1 = $stmt1->fetch(\PDO::FETCH_ASSOC);
                    $count = $data1['count'];

                    if($count) {
                        // --- 判断分页 ---
                        $page = isset($_GET['page']) && trim($_GET['page']) != '' ? intval($_GET['page']) : 1;

                        \C\lib\Page::setParam($count, self::listRows, $page, 10);
                        \C\lib\Page::setConfig('prev', '<<');
                        \C\lib\Page::setConfig('next', '>>');
                        \C\lib\Page::setConfig('first', '首页');
                        \C\lib\Page::setConfig('last', '尾页');
                        \C\lib\Page::setConfig('theme', "共 %TOTAL_ROW% 条记录( %NOW_PAGE% / %TOTAL_PAGE% 页) %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");

                        $limit1 = ($page - 1) * self::listRows;


                        $jWorkerType = [];
                        $workerTypes = workerType::getList([]);

                        foreach($workerTypes as $v) {
                            if(isset($jWorkerType[$v->worker_id])) $jWorkerType[$v->worker_id] .= $_WORKER_TYPE[$v->type] . ','; else $jWorkerType[$v->worker_id] = $_WORKER_TYPE[$v->type] . ',';
                        }

                        $city = \C\mod\city::getList([]);
                        $mycity = [];
                        foreach($city as $v) {
                            $mycity[$v->id] = $v->name;
                        }

                        $rflag = ctr::canResetPassword(); // 是否具有　重置密码　权限

                        $jWorkers = [];
                        $search = [];
                        $searchRealname? $search[] = ['realname', 'like','%'.$searchRealname.'%']:'';

                        $workers = worker::getList($search, [$limit1, self::listRows], ['id', 'desc']);

                        foreach($workers as $worker) {
                            $jWorkers[] = [
                                'id' => $worker->id,
                                'user1' => $worker->user,
                                'pwd_state' => $worker->pwd_state == '1' ? '是' : '否',
                                'phone' => $worker->phone, 'realname' => $worker->realname,
                                'time_add' => date('Y-m-d H:i:s', $worker->time_add), 'no' => $worker->no,
                                'title' => $worker->title,
                                'injob' => $worker->injob == '1' ? '在职' : '离职',
                                'workerType' => isset($jWorkerType[$worker->id]) ? rtrim($jWorkerType[$worker->id], ',') : '',
                                'city' => isset($mycity[$worker->city_id]) ? $mycity[$worker->city_id] :'',
                                'rbutton' => $rflag ? '<a href="javascript:;"uid="' . $worker->id . '"class="btn btn-primary resetPwd">重置密码</a> <a href="javascript:;"uid="' . $worker->id . '"class="btn btn-primary toEdit">编辑工种</a>' : ''
                            ];
                        }

                        $this->writeJson(1, ['workers' => $jWorkers , 'page'=>\C\lib\Page::show(), 'searchRN'=>$searchRealname]);
                    }else
                        $this->writeJson(0, '查无工作人员',1);
                }else
                    $this->writeJson(0, '查无工作人员',1);
            }else
                $this->writeJson(0, '请先登陆',1);

        }

        public function getCity() {



                $jCity[] = [
                    'id' => 1,
                    'name'=> 'aaa'
                ];
            $this->writeJson(1, ['city'=>$jCity]);
        }

        // --- 添加员工 ---
        public function add() {
            $this->writeJson(1, 1);
            if(hr::canAdministrative()) {

                if(isset($_POST['username']) && trim($_POST['username'])!='' && isset($_POST['phone']) && trim($_POST['phone'])!='' && isset($_POST['realname']) && trim($_POST['username'])!=''&& isset($_POST['workType']) && count($_POST['workType']) ) {
                    // $this->writeJson(1,$_POST,1);exit;
                    if(!Db::isConnected()) Db::connect();

                    if(!worker::get(['user1'=>$_POST['username']])) {
                        if(!worker::get(['realname'=>$_POST['realname']])) {

                            $res = Db::query('select min(no) no from cd_worker where no>11');
                            $data = $res->fetch(\PDO::FETCH_ASSOC);
                            if($data['no'] > 11) { // 数据库中预留工号从999到10
                                Db::beginTransaction();
                                $worker = new \C\mod\worker();
                                $worker->set([
                                            'user1' => $_POST['username'],
                                            'pwd' => 'b605e86d02eef8bfd0646f6a704c17c9',
                                            'salt' => '1234',
                                            'pwd_state' => 0,
                                            'realname' => $_POST['realname'],
                                            'time_add' => $_POST['startTime'] ? time($_POST['startTime']) : $_SERVER['REQUEST_TIME'],    //入职时间
                                            'time_out' => $_POST['endTime'] ? strtotime($_POST['startTime']) : 0, //离职时间
                                            'no' => $data['no'] - 1, //工号
                                            'city_id' => $_POST['city'] ? $_POST['city'] : 1,//所属城市,无的话默认为1表北京
                                            'phone' => $_POST['phone'], 'time_add' => $_SERVER['REQUEST_TIME']
                                        ]);

                                if($worker->create()) {
                                    // --- 添加工种 ---
                                    if(isset($_POST["workType"])) {
                                        $arrs = [];
                                        foreach($_POST['workType'] as $v) $arrs[] = ['worker_id' => $worker->id, 'type' => $v, 'defaults' => 0];

                                        count($arrs) ? $arrs[0]['defaults'] = 1 : '';

                                        $keyArr = array_keys($arrs[0]);
                                        $workerType = new \C\mod\workerType();
                                        $k = 0;
                                        do {
                                            if($k++ >= 3) {
                                                break;
                                            }   // 3次失败机会
                                            $result = $workerType->insert($keyArr, $arrs);
                                        } while(!$result);

                                        if($result) {
                                            // 若是集结点，添加为其初始化财务
                                            if(in_array('1',$_POST['workType'],true)) {
                                                $finace = new \C\mod\finance();
                                                $f = $finace->get(['worker_id'=>$worker->id]);
                                                if(!$f) {
                                                    $finace->set([
                                                        'worker_id' => $worker->id,
                                                        'balance' => 0,
                                                        'time_update' => $_SERVER['REQUEST_TIME']
                                                    ]);
                                                    if($finace->create()) {
                                                        Db::commit();
                                                        $this->writeJson(1, [], 1);
                                                    }else {
                                                        Db::rollBack(); // 执行失败，事务回滚
                                                        $this->writeJson(0, '财务系统为该员工建立财务档案失败');
                                                    }
                                                }else {
                                                    Db::rollBack(); // 执行失败，事务回滚
                                                    $this->writeJson(0, '已存在该员工财务信息，无法重新为该员工建立财务信息ＩＤ：'.$worker->id);
                                                }
                                            }else {
                                                //非集结点，无需建立财务档案，添加成功
                                                Db::commit();
                                                $this->writeJson(1, [], 1);
                                            }

                                        } else {
                                            Db::rollBack(); // 执行失败，事务回滚
                                            $this->writeJson(0, '数据库workerType表添加失败');
                                        }
                                    } else {
                                        Db::rollBack(); // 执行失败，事务回滚
                                        $this->writeJson(0, '创建失败，请选择该员工工种');
                                    }
                                } else
                                    $this->writeJson(0, '数据库worker表添加失败');
                            } else
                                $this->writeJson(0, '预留工号已使用完请重新设置');
                        } else
                            $this->writeJson(0, '真实姓名：'.$_POST['realname'].'已存在，请更换');
                    } else
                        $this->writeJson(0, '用户名：'.$_POST['username'].'已存在，请更换');
                } else
                    $this->writeJson(0, '传递数据错误或缺失,请检查必填项是否都已填写内容');
            }else
                $this->render('user1/main',['err'=>'无此操作权限']);

        }

    // --- 重置密码 ---
    public function ressetPwd() {
        if(ctr::canResetPassword()) {
            if(isset($_POST['uid']) && trim($_POST['uid']) != '') {
                $worker = new \C\mod\worker();
                $f = $worker->get(['id' => $_POST['uid']]);
                if($f) {
                    $pre = Db::prepare('UPDATE ' . DB_PRE . 'worker SET pwd="b605e86d02eef8bfd0646f6a704c17c9", salt ="1234" WHERE id=:id');
                    $pre->execute([':id' => $_POST['uid']]);
                    if($pre->rowCount() >= 0) {
                        $this->writeJson(1, [], 1);
                    }else
                        $this->writeJson(0, '重置用户密码失败，用户名：'.$f->realname.'('.$_POST['uid'].':'.$f->user.')');
                }else
                    $this->writeJson(0, '查无此ＩＤ用户（id:'.$_POST['uid'].'）');
            }
        }else
            $this->render('user1/main',['err'=>'未登陆或无此操作权限']);
    }

    // --- 显示员工信息 ---
    public function toEditWorktype() {
        if(ctr::canResetPassword()) {
            if(isset($_POST['uid']) && trim($_POST['uid']) != '') {
                if($worker=worker::get(['id'=>$_POST['uid']])) {
                    $workType = \C\mod\workerType::getList(['worker_id' => $_POST['uid']]);

                    $jWorkType = [];
                    foreach($workType as $w) {
                        $jWorkType[] = ['type' => $w->type, 'default' => $w->defaults];
                    }
                    $this->writeJson(1, ['workType' => $jWorkType, 'worker' => ['id' => $worker->id, 'name' => $worker->user, 'realname' => $worker->realname,'city_id'=>$worker->city_id]]);
                }else
                    $this->writeJson(0, '查无此ＩＤ用户（id:'.$_POST['uid'].'）');
            }else
                $this->writeJson(0, '查无此用户ＩＤ传入');
        }else
            $this->render('user1/main',['err'=>'未登陆或无此操作权限']);
    }

    // --- 编辑员工信息 ---
    public function doEditWorktype() {
        if(hr::canAdministrative()) {

            if(isset($_POST['id']) && trim($_POST['id'])!='' && isset($_POST['username']) && trim($_POST['username'])!='' && isset($_POST['city']) && trim($_POST['city'])!='' && isset($_POST['realname']) && trim($_POST['realname'])!=''&& isset($_POST['wtype']) && count($_POST['wtype']) ) {

                if($worker=worker::get(['id'=>$_POST['id']])) {
                    $stmt = Db::prepare('SELECT id FROM ' . DB_PRE . 'worker WHERE user1=:user1 and id!=:id');
                    $stmt->execute([':user1'=>$_POST['username'], ':id'=>$_POST['id']]);
                    if(($stmt->execute()) && $stmt->rowCount() <= 0) {

                        $stmt = Db::prepare('SELECT id FROM ' . DB_PRE . 'worker WHERE realname=:realname and id!=:id');
                        $stmt->execute([':realname'=>$_POST['realname'], ':id'=>$_POST['id']]);
//                    if(!worker::get(['user1'=>$_POST['username'], 'id'])) {
//                        if(!worker::get(['realname'=>$_POST['realname']])) {
                        if(($stmt->execute()) && $stmt->rowCount() <= 0) {
                            $pre = Db::prepare('UPDATE ' . DB_PRE . 'worker SET user1=:user1, realname=:realname, city_id=:city_id  WHERE id=:id');
                            $pre->execute([
                                    ':id' => $_POST['id'],
                                    ':user1' => trim($_POST['username']),
                                    ':realname' => trim($_POST['realname']),
                                    ':city_id' => trim($_POST['city'])
                                ]);
                            if($pre->rowCount() >= 0) {
                                $oldwt = $_POST['oldWorkType'];
                                if(implode(',', $_POST['wtype']) === $oldwt) {
                                    $this->writeJson(2, [], 1);
                                }else {
                                    // --- 删除指定用户旧的工种 ---
                                    DB::beginTransaction();
                                    $pre = Db::prepare('DELETE FROM ' . DB_PRE . 'worker_type WHERE worker_id=:worker_id');
                                    $pre->execute([':worker_id' => $_POST['id']]);
                                    if($pre->rowCount() >= 0) {
                                        // --- 插入该用户新的工种 ---
                                        $worktype = new \C\mod\workerType();
                                        $arr = [];$flag = true;
                                        foreach($_POST['wtype'] as $v) {
                                            $arr[] = [
                                                'worker_id' => $worker->id,
                                                'type' => $v,
                                                'defaults' => $flag? 1 :0
                                            ];
                                            $flag = false;
                                        }
                                        $sql = new \C\lib\sql();
                                        $sql->insert('worker_type',['worker_id','type','defaults'], $arr);
                                        if(Db::exec($sql->sql)) {
                                            DB::commit();
                                            $this->writeJson(1, [], 1);
                                        }else {
                                            DB::rollBack();
                                            $this->writeJson(0, '编辑用户工种信息失败2，用户名：'.$worker->realname.'('.$_POST['id'].':'.$worker->user.')');
                                        }
                                    }else
                                        $this->writeJson(0, '编辑用户工种信息失败1，用户名：'.$worker->realname.'('.$_POST['id'].':'.$worker->user.')');
                                }
                            }else
                                $this->writeJson(0, '编辑用户信息失败，用户名：'.$worker->realname.'('.$_POST['id'].':'.$worker->user.')');
                        } else
                            $this->writeJson(0, '真实姓名：'.$_POST['realname'].'已存在，请更换');
                    } else
                        $this->writeJson(0, '登录名：'.$_POST['username'].'已存在，请更换');
                }else
                   $this->writeJson(0, '查无此ＩＤ用户（id:'.$_POST['uid'].'）');
            } else
                $this->writeJson(0, '传递数据错误或缺失,请检查必填项是否都已填写内容');
        }else
            $this->render('user1/main',['err'=>'无此操作权限']);
    }
}

